const Koa = require('koa');
const Router = require('koa-router');
const multer = require('@koa/multer');
const path = require('path')
const fs = require('fs')
const static = require('koa-static')


const app = new Koa();
const router = new Router()
const upload = multer(); 

const imagesPath = path.resolve('static', 'images')

// 处理静态资源
app.use(static(imagesPath))

// 上传接口
router.post(
    '/upload',
    upload.single('chunk'),
    async ctx => {
      const { originalname } = ctx.request.file; // 1.webp
      const time = new Date().getTime();  //  12312312312312311231
      const [name, ext] = originalname.split('.');
      const pathname = name + '-' +time + '.' + ext
      await fs.promises.writeFile(
        path.join(imagesPath, pathname),
        ctx.request.file.buffer
      )
      ctx.body = ({
        code: 200,
        data: {
            message: '上传图片成功过',
            url: `http://10.1.129.15:8000/${pathname}`
        }
    })
    }
  );


// 启动路由
app.use(router.routes())
// 运行所有请求方式
app.use(router.allowedMethods())
// 启动服务
app.listen(8000, () => {
    console.log('服务器在8000端口启动了！！！')
})